package features.advance.jdk.annotation;

//import org.springframework.boot.SpringApplication;
//import org.springframework.boot.autoconfigure.SpringBootApplication;
//import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
//import org.springframework.context.annotation.ComponentScan;

import sun.misc.Unsafe;

import javax.annotation.processing.Processor;
import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.ServiceLoader;

/**
 * 注解annotationType和getClass的区别
 *
 * @author LIN
 * @date 2021-07-12
 */
//@SpringBootApplication
public class Demo
//        extends SpringBootServletInitializer
{

    @AnnotationDemo(name = "hello world")
    private String test;

    private static final Unsafe unsafe = getUnsafeInstance();

    private long address = 0;

    // 让对象占用堆内存，触发Full GC
    private byte[] bytes = null;

    public Demo(){
        address = unsafe.allocateMemory(2 * 1024 * 1024);
        bytes = new byte[1024 * 1024];
    }


    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        System.out.println("finalize."+bytes.length);
        // 手动释放堆外内存
        unsafe.freeMemory(address);

    }

    private static Unsafe getUnsafeInstance() {
        if(unsafe == null){
            try{
                Field f = Unsafe.class.getDeclaredField("theUnsafe");
                f.setAccessible(true);
                Unsafe us = (Unsafe) f.get(null);
                return us;
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return unsafe;
    }


    public static void main(String[] args) throws Exception {
        ServiceLoader<Processor> load = ServiceLoader.load(Processor.class);
        Iterator<Processor> iterator = load.iterator();
        if(iterator.hasNext()){
            Processor next = iterator.next();
        }

        //Exception in thread "main" java.lang.SecurityException: Unsafe
        while(true){
            Demo demo = new Demo();
            System.out.println("memory address=" +demo.address);
        }



    }
//    public static void main(String[] args) {
//        SpringBootApplication springBootApplication = Demo.class.getAnnotation(SpringBootApplication.class);
//        Class<? extends Annotation> annotationType = springBootApplication.annotationType();
//        Class<? extends SpringBootApplication> springBootApplicationClass = springBootApplication.getClass();
//        ComponentScan annotation = annotationType.getAnnotation(ComponentScan.class);
//        ComponentScan annotation1 = springBootApplicationClass.getAnnotation(ComponentScan.class);
//        SpringApplication.run(Demo.class,args);
//
//
//    }
}
